package com.lanyun.auth.domain.authUserRole.impl;


import com.lanyun.auth.basic.entity.AuthUser;
import com.lanyun.auth.basic.entity.AuthUserRole;
import com.lanyun.auth.basic.service.AuthUserRoleService;
import com.lanyun.auth.basic.service.AuthUserService;
import com.lanyun.auth.controller.admin.authUserRole.vo.AuthUserRoleRequestVO;
import com.lanyun.auth.domain.authUserRole.AuthUserRoleDomainService;
import com.lanyun.redis.util.CacheKey;
import com.lanyun.redis.util.RedisUtil;
import com.lanyun.web.enums.IsDeletedFlagEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/3/12
 */
@Service
public class AuthUserRoleDomainServiceImpl implements AuthUserRoleDomainService {

    @Resource
    private AuthUserRoleService authUserRoleService;

    @Resource
    private AuthUserService authUserService;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public Boolean addUserRole(AuthUserRoleRequestVO authUserRoleRequestVO) {

        List<Long> roleIds = authUserRoleRequestVO.getRoleIds();
        Long userId = authUserRoleRequestVO.getUserId();


        roleIds.forEach(roleid -> {
            AuthUserRole authUserRole = new AuthUserRole();
            authUserRole.setUserId(userId);
            authUserRole.setRoleId(roleid);
            authUserRole.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
            /**
             * 从用户角色表中没有查到对应的数据，此时再去关联这个用户角色
             */
            List<AuthUserRole> authUserRoles = authUserRoleService.queryAllByCondition(authUserRole);
            if (CollectionUtils.isEmpty(authUserRoles)) {
                authUserRoleService.insert(authUserRole);
            }
        });


        /**
         * 将redis中的角色和权限删除掉，在用户获取权限时在重新刷入
         */
        try {
            AuthUser authUser = authUserService.queryById(userId);
            String permissionKey = redisUtil.buildKey(CacheKey.AUTH_PERMISSION.getCachePrefix(), authUser.getUsername());
            String roleKey = redisUtil.buildKey(CacheKey.AUTH_ROLE.getCachePrefix(), authUser.getUsername());
            redisUtil.del(permissionKey);
            redisUtil.del(roleKey);
        } catch (Exception e) {
            return false;
        }

        return true;
    }
}
